# -*- coding: utf-8 -*-
# @Date：2024/7/22 22:54:26
# @Author：CJiaの青姝
# @FileName：cj_export
# @Editor：PyCharm2024
# @Remark：
import json

import numpy as np
import pandas as pd


def export_data(request, file, check):
    # 读取Excel文件
    data_frame = pd.read_excel(file)
    # 将DataFrame转换为字典列表
    data_list = data_frame.to_dict(orient='records')
    # 过滤数据
    result = check_data(data_list, check)
    # 返回结果
    return result


def check_data(data, check):
    """
    检查数据是否为空
    :param data: Excel文件中读取的字典列表
    :param check: 需要检查的字段
    :return:
    """
    index_list = []
    result = {
        "error": [],
        "success": [],
    }
    for index, value in enumerate(data):
        for key in check:
            if isinstance(value[key], float):
                if np.isnan(value[key]):
                    index_list.append(index)
                    result['error'].append({f"行号：{index + 2} --- {key}：输入语法格式有误"})
    for index, value in enumerate(data):
        if index not in index_list:
            result['success'].append(value)
    # 返回处理后的数据
    return result


def deal_chinese_key(data_list, relation):
    """
    处理Excel文件中中文key的问题
    :param data_list: Excel文件中读取的字典列表
    :param relation: 对应的key关系
    :return:
    """
    result = {
        "error": data_list['error'],
        "success": [],
    }
    for data in data_list['success']:
        temp = {}
        for key, value in data.items():
            if key in relation:
                temp[relation[key]] = value
            else:
                temp[key] = value
        result['success'].append(temp)
    return result


def repeat_data(model, data, repeat, multiple):
    """
    检查数据是否重复
    :param model: 检查的模型
    :param data: 检查的数据
    :param repeat: 重复的字段
    :param multiple: 多重判断
    :return:
    """
    index_list = []
    result = {
        "error": [],
        "success": [],
    }
    for index, value in enumerate(data):
        for obj in repeat:
            if multiple:
                if model.objects.filter(
                        **{obj['model']: value[obj['name']], obj['multiple_model']: value[obj['multiple']]}).exists():
                    index_list.append(index)
                    result['error'].append({f"行号：{index + 2} --- {obj['name']}：输入值已存在"})
            else:
                if model.objects.filter(**{obj['model']: value[obj['name']]}).exists():
                    index_list.append(index)
                    result['error'].append({f"行号：{index + 2} --- {obj['name']}：输入值已存在"})
    for index, value in enumerate(data):
        if index not in index_list:
            result['success'].append(value)
    return result


# def repeat_data(model, data, repeat, multiple):
#     """
#     检查数据是否重复
#     :param model: 检查的模型
#     :param data: 检查的数据
#     :param repeat: 重复的字段
#     :param multiple: 多重判断
#     :return:
#     """
#     index_list = []
#     result = {
#         "error": [],
#         "success": [],
#     }
#     for index, value in enumerate(data):
#         for obj in repeat:
#             if multiple:
#                 if model.objects.filter(
#                         **{obj['model']: value[obj['field']], obj['multiple']: value[obj['multiple']]}).exists():
#                     index_list.append(index)
#                     result['error'].append({f"行号：{index + 2} --- {obj['name']}：输入值已存在"})
#             else:
#                 if model.objects.filter(**{obj['model']: value[obj['field']]}).exists():
#                     index_list.append(index)
#                     result['error'].append({f"行号：{index + 2} --- {obj['name']}：输入值已存在"})
#     for index, value in enumerate(data):
#         if index not in index_list:
#             result['success'].append(value)
#     return result


def parent_data(model, data, parent):
    index_list = []
    result = {
        "error": [],
        "success": [],
    }
    for index, value in enumerate(data):
        for obj in parent:
            queryset = model.objects.filter(**{obj['model']: value[obj['name']]}).first()
            if queryset:
                value[obj['name']] = queryset.id
            else:
                index_list.append(index)
                result['error'].append({f"行号：{index + 2} --- {obj['name']}：不存在"})
    for index, value in enumerate(data):
        if index not in index_list:
            result['success'].append(value)
    return result
